package com.lst.demo.ui;

import android.content.Intent;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lst.demo.R;
import com.lst.demo.preview.MyPreviewActivity;
import com.lst.demo.preview.TestImageLoader;
import com.lst.demo.preview.UserViewInfo;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.previewlibrary.GPreviewBuilder;
import com.previewlibrary.ZoomMediaLoader;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

public class PictureActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_picture);
        ZoomMediaLoader.getInstance().init(new TestImageLoader());
        findViewById(R.id.btn_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                takePic();
            }
        });

        findViewById(R.id.btn_preview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                List<UserViewInfo> stringList = new ArrayList<>();
                UserViewInfo userViewInfo = new UserViewInfo("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=2279952540,2544282724&fm=26&gp=0.jpg");
                stringList.add(userViewInfo);

                Bundle bundle = new Bundle();
                bundle.putString("url", userViewInfo.getUrl());

                GPreviewBuilder.from(PictureActivity.this)
                        // .setData(stringList)
                        .to(MyPreviewActivity.class, bundle)
                       // .setDuration(500)
                        .setSingleData(userViewInfo)
                        .setSingleShowType(false)//只有一张图片时不显示指示器
                        .setCurrentIndex(0)
                        .setSingleFling(true)//是否在黑屏区域点击返回
                        .setDrag(true)//是否禁用图片拖拽返回
                        // .setType(GPreviewBuilder.IndicatorType.Dot)//指示器类型
                        .start();//启

            }
        });

    }

    /**
     * 拍照
     */
    public void takePic() {

//        String filePath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/";
        //   String filePath = Environment.getExternalStorageDirectory().getPath() + "/Picture/lstdemo/";
        //  String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/lstdemo";
        //  String filePath ="lstdemo";

//        File file = new File(filePath);
//        if (!file.exists()) {
//            file.mkdirs();
//        }
//        if (!file.exists()) {
//            Toast.makeText(this, "获取路径失败", Toast.LENGTH_SHORT).show();
//            return;
//        }

        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                //  .setOutputCameraPath(filePath)
                .enableCrop(false)// 是否裁剪 true or false
                // .compress(true)
                //.cropCompressQuality(80)
                .forResult(PictureConfig.REQUEST_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {

            if (requestCode == PictureConfig.REQUEST_CAMERA) {
                List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                final String path = localMedia.get(0).getPath();//拍照路径
                final File file = new File(path);
                String fileName = file.getName();
                LogUtils.i("拍照路径:" + path);

                ToastUtils.showLong("图片已保存至/storage/emulated/0/Pictures/" + fileName + " 文件夹");

                // 其次把文件插入到系统图库  路径: 手机存储/Pictures/xxx.PNG
                try {
                    MediaStore.Images.Media.insertImage(getContentResolver(),
                            file.getAbsolutePath(), fileName, null);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // 最后通知图库更新
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 判断SDK版本是不是4.4或者高于4.4
                    String[] paths = new String[]{file.getAbsolutePath()};
                    MediaScannerConnection.scanFile(this, paths, null, null);
                } else {
                    final Intent intent;
                    if (file.isDirectory()) {
                        intent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
                        intent.setClassName("com.android.providers.media", "com.android.providers.media.MediaScannerReceiver");
                        intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
                    } else {
                        intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        intent.setData(Uri.fromFile(file));
                    }
                    sendBroadcast(intent);
                }


                FileUtils.delete(file);

                //保存到相册
//                File file1 = ImageUtils.save2Album(ImageUtils.getBitmap(file), "lstdemo", Bitmap.CompressFormat.PNG);
//                if (file1.exists()) {
//                    //  boolean delete = FileUtils.delete(file);
//                    LogUtils.i("拍照删除原来的图片:");
//                }


               /* //保存图片到指定目录
                boolean save = ImageUtils.save(ImageUtils.getBitmap(file), Environment.getExternalStorageDirectory().getPath() + "/Pictures/lstdemo/"+file.getName(), Bitmap.CompressFormat.PNG);
                LogUtils.i("拍照保存到指定目录:" + save);
                if (save) {
                    //保存成功,删除原来的图片
                    boolean delete = FileUtils.delete(file);
                    LogUtils.i("拍照删除原来的图片:" + delete);

                }*/


            }
        }

    }
}
